//
//  YRYHomeTopHeaderView.m
//  luGongPro
//
//  Created by 王庆学 on 2017/7/26.
//  Copyright © 2017年 王庆学. All rights reserved.
//

#import "YRYHomeTopHeaderView.h"
#import "EFSTopBannerView.h"
#import "YRYHomeTopHeaderCell.h"
#import "YRYHomeTopHeaderFlowLayout.h"
#import "YRYHomeTopHeaderQuotationFlowLayout.h"
#import "CustomizedQuoteViewModel.h"
#import "YSUserManager.h"
#import "YGHomeTopItemManager.h"
#import "YGQuotationSubsriber.h"

@interface YRYHomeTopHeaderView ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>
@property (strong, nonatomic) IBOutlet UIView *contentView;

@property (weak, nonatomic) IBOutlet EFSTopBannerView *bannerView;

@property (weak, nonatomic) IBOutlet UICollectionView *topCollectionView;

@property (weak, nonatomic) IBOutlet UICollectionView *quotationView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *TopBannerViewHeightConstraint;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *QuationViewTopConstraintFromTopView;

@property (weak, nonatomic) IBOutlet UILabel *CustomizedQuoteIndexPageLabel;

@property (nonatomic, strong) NSMutableArray *topDataSource;

@property (nonatomic, assign) NSInteger numberOfQuotePages;

@property (nonatomic, strong) YGQuotationSubsriber *subsriber;

@property (nonatomic, assign) NSInteger pageIndex;


@end

@implementation YRYHomeTopHeaderView

- (void)awakeFromNib{
    [super awakeFromNib];
    [self.topCollectionView registerClass:NSClassFromString(@"YRYHomeTopHeaderCell") forCellWithReuseIdentifier:@"YRYHomeTopHeaderCell"];
    [self.bannerView startBannerScrolling];
    [self.quotationView registerNib:[UINib nibWithNibName:@"" bundle:nil] forCellWithReuseIdentifier:@""];
    [self.quotationView registerNib:[UINib nibWithNibName:@"" bundle:nil] forCellWithReuseIdentifier:@""];
    [self.quotationView registerNib:[UINib nibWithNibName:@"" bundle:nil] forCellWithReuseIdentifier:@""];
    [self bindMainCollectionViewRac];
    [self.bannerView launch];
    
    @weakify(self);
    [RACObserve([YSUserManager sharedManager], currentUser) subscribeNext:^(id x) {
        @strongify(self);
        NSArray *types = nil;
        if (![YSUserManager sharedManager].hasTradeAccount){
            types = @[@(YGHomeTopItemTypeSignUpNowModel),
                      @(YGHomeTopItemTuoGuan),
                      @(YGHomeTopItemFashou),
                      @(YGHomeTopItemTypeMarketCenter)];
        }else{
            types = @[@(YGHomeTopItemTradeCenter),
                      @(YGHomeTopItemTuoGuan),
                      @(YGHomeTopItemFashou),
                      @(YGHomeTopItemTypeMarketCenter),
                      ];
        }
        self.topDataSource = [NSMutableArray array];
        for (NSNumber *type in types){
            [self.topDataSource addObject:[YGHomeTopItemManager creatModelWithType:type.integerValue]];
        }
        [self.topCollectionView reloadData];
    }];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]){
        self.contentView = [[[NSBundle mainBundle]loadNibNamed:@"YRYHomeTopHeaderView" owner:self options:nil]firstObject];
        self.contentView.frame = self.bounds;
        [self addSubview:self.contentView];
    }
    return self;
}

#pragma mark - subscribe andunSubscribe
- (void)subscribeCurrentVisibleQuote{
    for (int i = 0; i < 3; i++){
        int index = (int)self.pageIndex * 3 + i;
        if (index < self.customizedQuoteList.count){
            CustomizedQuoteViewModel *viewModel = self.customizedQuoteList[self.pageIndex *3 + i];
            YSSecurities *quote = viewModel.securities;
            [self.subsriber addSubsribeWithQuotationID:quote.IdStr];
        }
    }
    [self.subsriber resume];
}

- (void)unSubcribeCurrentQuote{
    [self.subsriber cancel];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self subscribeCurrentVisibleQuote];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.subsriber cancel];
}

#pragma mark - Main Collection View
- (void)bindMainCollectionViewRac{
    @weakify(self);
    [RACObserve(self.bannerView, bannerList) subscribeNext:^(NSArray *bannerList) {
        @strongify(self);
        CGRect frame = self.frame;
        if (!bannerList || bannerList.count == 0){
            self.TopBannerViewHeightConstraint.constant = 0;
            self.QuationViewTopConstraintFromTopView.constant = 180-86;
            frame.size.height = 320 - 86;
        }else{
            self.TopBannerViewHeightConstraint.constant = [YSUtil getLenght:TopBannerHeightConstraintOriginValue];
            self.QuationViewTopConstraintFromTopView.constant = 180 - 86 + [YSUtil getLenght:TopBannerHeightConstraintOriginValue];
            frame.size.height = 320 - 86 + [YSUtil getLenght:TopBannerHeightConstraintOriginValue];
        }
        self.frame = frame;
        if ([self.delegate respondsToSelector:@selector(changeHeightOfHeaderView:)]){
            [self.delegate changeHeightOfHeaderView:self];
        }
        [self updateConstraints];
    }];
    
    [RACObserve(self.quotationView, contentOffset) subscribeNext:^(id x) {
        @strongify(self);
        NSValue *value = (NSValue *)x;
        CGPoint offset = [value CGPointValue];
        NSInteger index = fabs(offset.x) / self.quotationView.frame.size.width;
        self.pageIndex = index;
        self.CustomizedQuoteIndexPageLabel.text = [NSString stringWithFormat:@"(%@/%@)",@(index+1),@(_numberOfQuotePages)];
    }];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    if (collectionView == self.quotationView){
        return CGSizeMake(collectionView.frame.size.width / 3, self.quotationView.bounds.size.height);
    }
    else if (collectionView == self.topCollectionView){
        return CGSizeMake((kWidth - 20) / 4, self.topCollectionView.bounds.size.height);
    }else{
        return CGSizeZero;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.topCollectionView){
        return self.topDataSource.count;
    }else if (collectionView == self.quotationView){
        return self.customizedQuoteList.count;
    }
    return 0;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.topCollectionView){
        YRYHomeTopHeaderCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YRYHomeTopHeaderCell" forIndexPath:indexPath];
        YGHomeTopItemModel *model = self.topDataSource[indexPath.item];
    }
    return nil;
}

- (void)setCustomizedQuoteList:(NSMutableArray *)customizedQuoteList{
    _customizedQuoteList = customizedQuoteList;
    self.numberOfQuotePages = (int)((self.customizedQuoteList.count + 3 -1) / 3);
    [self.quotationView reloadData];
    [self subscribeCurrentVisibleQuote];
}

- (void)reloadData{
    [self.bannerView launch];
}

- (void)dealloc{
    [self.bannerView stopBannerScrolling];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
